package cn.wujiangbo.utils.excel;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.wujiangbo.domain.User;
import cn.wujiangbo.utils.MyTools;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 往Excel中写测试数据的工具类
 */
public class ExcelWriterTools {

    public static void main(String[] args) {
        //create1();
        create2();
    }

    //第一种方式：利用单线程执行任务
    public static void create1(){
        Long t1 = System.currentTimeMillis();
        for(int i=1; i<=50; i++){
            createExcel("E:/excel/testExcel_" + MyTools.getRandomLength(6) + ".xlsx");
        }
        Long t2 = System.currentTimeMillis();
        System.out.println("耗时：" + (t2-t1) + "毫秒");
    }

    //第二种方式：利用多线程执行任务
    public static void create2(){
        Long t1 = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(20);
        for(int i=1; i<=20; i++){
            new Thread(() -> {
                System.out.println("线程：" + Thread.currentThread().getName() + "开始执行了........");
                createExcel("E:/excel/testExcel_" + MyTools.getRandomLength(6) + ".xlsx");
                latch.countDown();
            }).start();
        }
        try {
            latch.await();//等待所有线程执行完毕
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Long t2 = System.currentTimeMillis();
        System.out.println("生成Excel完成啦，耗时：" + (t2-t1) + "毫秒");
    }

    //生成Excel
    public static void createExcel(String filePath){
        //构建测试数据
        List<User> userList = MyTools.getTestUserList(2000, true);
        //写出数据到Excel
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(filePath);
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(userList, true);
        // 关闭writer，释放内存
        writer.close();
    }
}
